package com.ssh;

import java.util.Stack;

import org.junit.Test;

public class IsValid_20 {
	public boolean isValid(String s) {
		Stack<Character> stack = new Stack<Character>();
		boolean b = true;
		int y;
        for (int i = 0; i < s.length(); i++) {
        	char x = s.charAt(i);
        	if (x == '{' || x == '[' || x == '(') {
        		stack.push(x);
        	}else if (x == '}' || x == ']' || x == ')') {
        		if (!stack.isEmpty()) {
        			y = stack.pop();
        		}else {
        			return false;
        		}
        		b = ( (y == ((int)x-1)) || (y == ((int)x-2)) );
        		if (b == false) {
        			return false;
        		}
        	}
        }
        return stack.isEmpty();
    }
	/**
	 * 如果含有其他字母，算法失效，还是我写的牛b，请看上一个算法
	 * @param s
	 * @return
	 */
	public boolean isValid1(String s) {
		Stack<Character> stack = new Stack<Character>();
		for (char c : s.toCharArray()) {
			if (c == '{') {
				stack.push('}');
			}else if (c == '[') {
				stack.push(']');
			}else if (c == '(') {
				stack.push(')');
			}else if (stack.isEmpty() || c != stack.pop()) {
				return false;
			}
		}
		return stack.isEmpty();
	}
	
	@Test
	public void test () {
		String s = "{s[s(s)]aa}";
		System.out.println(isValid(s));
	}
}
